#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.dev'

import django
django.setup()

from django_redis import get_redis_connection
import requests, json, base64, time, logging
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcsl_v1_5
from Crypto.PublicKey import RSA

from wxapi.utils import wyf_access_token

logger = logging.getLogger('django')


def update_gzh_accesstoken():
    url = 'http://api.wpost.cn/wxapi/accesstoken'
    response = requests.get(url)
    data = response.json()
    redis_conn = get_redis_connection("gzh_accesstoken")
    redis_conn.set("gzh_accesstoken", data['accesstoken'])
    return data['accesstoken']


def ali_fundtrans_template(order_id, amount, remark):
    redis_conn1 = get_redis_connection("gzh_accesstoken")
    gzh_accesstoken = redis_conn1.get("gzh_accesstoken")
    if not gzh_accesstoken:
        access_token = update_gzh_accesstoken()
    else:
        access_token = gzh_accesstoken.decode()
    # access_token = '63_LcpmmT8PCB13Ru7ZzmrHOE882VoK5OkxMYYi3Sh1LxqZwHlhpp_ltQOtcqWEnRpVb4DLS2afGxUgRGQzWqn-mkO4CNNqygmNvp3P8q3pobYRb1IZmeYcvkMd9zwGANaAHAKER'
    for user in ['oyNYvwxo79BpNAXQ4aRz-Wwgwfps', 'oyNYvw0oN6GX0F4gvbEjbNjrLmJg', 'oyNYvw5wNQDfrttJXqoJbm93vYuY']:
    # for user in ['oyNYvw7MNNqB7-NVdwfCjx2ErRq0', 'oyNYvw0oN6GX0F4gvbEjbNjrLmJg']:
        data = {
            "touser": user,
            "template_id": "XB30WUBqXZ7QoZT4mqB331NC_gAUPOguJytU0ClM288",
            "data": {
                "first": {
                    "value": f'支付宝消费金打款失败!',
                    "color": "#ed6f56"
                },
                "keyword1": {
                    "value": f'订单号{order_id}',
                    "color": "#878787"
                },
                "keyword2": {
                    "value": f'金额{amount}',
                    "color": "#878787"
                },
                "remark": {
                    "value": remark,
                    "color": "#ed6f56"
                }
            }
        }
        headers1 = {"Content-Type": "application/json"}
        response = requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}', data=json.dumps(data), headers=headers1)
        if response.json()['errcode'] != 0:
            access_token = update_gzh_accesstoken()
            response = requests.post(url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',data=json.dumps(data), headers=headers1)
        print(response.json())
    return ''


def update_wyfgzh_accesstoken():
    url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7da420ea681c863a&secret=7057b94cc7f6fcc9d8355aabe99367d5'
    response = requests.get(url=url)
    result = response.json()
    access_token = result['access_token']
    expires_in = result['expires_in']
    redis_conn = get_redis_connection("gzh_accesstoken")
    redis_conn.setex("wyf_access_token", expires_in, access_token)
    return access_token


def invite_push_notification(openid, data1):
    redis_conn = get_redis_connection("gzh_accesstoken")
    access_token = redis_conn.get("wyf_access_token")
    if not access_token:
        access_token = wyf_access_token()
    else:
        access_token = access_token.decode()
    headers = {"Content-Type": "application/json"}
    data = {
        "touser": openid,
        "template_id": "wBE5cY_MN5WKlzEuDH9y2kL2YHMiJfktIsRTduC7pX0",
        "miniprogram": {
            "appid": "wx950122ad80dc97c9",
            "pagepath": "pages/mer_market_invite/mer_market_invite"
        },
        "data": data1
    }
    response = requests.post(
        url=f'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}',
        data=json.dumps(data), headers=headers)
    logger.info((str(response.json()), openid))
    print(response.json())



if __name__ == '__main__':
    # ali_fundtrans_template('3126', 100.00, '收款账号不存在或姓名有误，建议核实账号和姓名是否准确')
    data = {
        "keyword1": {
            "value": "已成功邀请1位用户",
            "color": "#878787"
        },
        "keyword2": {
            "value": "点击立即进入",
            "color": "#878787"
        },
        "keyword3": {
            "value": "微邮惠商圈",
            "color": "#ed6f56"
        },
        "keyword4": {
            "value": "查看邀请进度",
            "color": "#ed6f56"
        },
        "keyword5": {
            "value": "邀请任务完成即可参与抽奖！",
            "color": "#ed6f56"
        }
    }
    invite_push_notification('onCMAuG8Cp77psc05GL8tyBqfMEk', data)
